package com.zkq.graduate.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zkq.graduate.annotation.LimitTime;
import com.zkq.graduate.enums.ResponseEnum;
import com.zkq.graduate.pojo.Student;
import com.zkq.graduate.pojo.StudentVo;
import com.zkq.graduate.pojo.StudentWithReport;
import com.zkq.graduate.pojo.Title;
import com.zkq.graduate.service.*;
import com.zkq.graduate.util.LocalDateTimeUtil;
import com.zkq.graduate.util.ResultHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author zhangkaiqiang
 * @Date 2019/11/29  10:41
 * @Description TODO
 * 学生控制类
 */

@RestController
@RequestMapping("/api/v1/student")
@Api(tags = {"学生模块接口"})
public class StudentController {


	@Resource(name = "titleService")
	private TitleService titleService;

	@Resource(name = "studentService")
	private StudentService studentService;

	@Resource(name = "selectedTitleService")
	private SelectedTitleService selectedTitleService;

	@Resource(name = "mongoService")
	private MongoDbService mongoDbService;

	@Resource(name="fileRecordService")
	private FileRecordService fileRecordService;


	@com.zkq.graduate.annotation.Student
	@GetMapping("/titles")
	@LimitTime
	@ApiOperation(value = "学生查看所有可选题目",notes = "带有分页操作")
	public ResultHandler<Title> listTitleByStudent(@RequestParam("page") int currentPage,
												   @RequestParam("limit") int pageSize,
												   HttpServletRequest request){
		String studentId= (String) request.getAttribute("account");
		List<Title> studentCanSelect=new ArrayList<>();
		if(StringUtils.isNotBlank(studentId)){
			Optional<Student> student=studentService.findByStudentId(studentId);
			PageHelper.startPage(currentPage,pageSize);
			if(student.isPresent()){
				studentCanSelect=titleService.listTitleByStudent(student.get());
			}
			PageInfo<Title> page=new PageInfo<>(studentCanSelect);
			return ResultHandler.success(page);
		}
		return ResultHandler.fail(ResponseEnum.SELECT_ERROR);
	}



	@com.zkq.graduate.annotation.Student
	@GetMapping("/selected-title")
	@ApiOperation(value = "查看学生选题记录,包含与指导教师达成双选以及被拒绝的选择")
	public ResultHandler<StudentVo> findStudentSelectedTitleInfo(HttpServletRequest request){

		String studentId= (String) request.getAttribute("account");
		if(StringUtils.isNotBlank(studentId)){
			List<StudentVo> studentVo=selectedTitleService.findStudentSelectedTitle(studentId);
			return ResultHandler.success(studentVo);
		}
		return ResultHandler.fail(ResponseEnum.SELECT_ERROR);
	}


	@PostMapping("/title/{titleId}")
	@com.zkq.graduate.annotation.Student
	@LimitTime
	@ApiOperation(value = "学生选择某个可选题目")
	public ResultHandler<String> selectOneTitle(@PathVariable("titleId") String titleId, HttpServletRequest request){

		String studentId= (String) request.getAttribute("account");
		if(StringUtils.isNotBlank(studentId)){
			// 判断学生是否已经选择了题目
			if(!studentService.findStudentIfSelected(studentId)){
				return ResultHandler.fail(ResponseEnum.ALREADY_SELECT_TITLE);
			}

			// 判断该可选题目是否达到可选人数上限
			Optional<Title> title=titleService.getTitleById(titleId);
			if(title.isPresent()){
				if(title.get().getSelectCount()>=title.get().getTotalCount()){
					return ResultHandler.fail(ResponseEnum.TITLE_UPPER_LIMIT);
				}
				title.get().setSelectCount(title.get().getSelectCount()+1);
				// 学生选择该可选题目--增长已选择人数与写选择表
				StudentVo studentVo=new StudentVo();
				studentVo.setStudentId(Integer.valueOf(studentId));
				studentVo.setSelectStatus("0");
				studentVo.setTitle(title.get());
				if(titleService.updateSelectCount(title.get())&&selectedTitleService.insertOneSelectTitle(studentVo)){
					return ResultHandler.success();
				}
			}
		}
		return ResultHandler.fail(ResponseEnum.INSERT_ERROR);
	}

	@PostMapping("/openAndPaper")
	@com.zkq.graduate.annotation.Student
	@LimitTime
	@ApiOperation(value = "学生上传毕业设计或者毕业论文")
	public ResultHandler<String> uploadPaper(
			HttpServletRequest request,
			MultipartFile file,
			String flag){
		if(file!=null){
			// 向mongodb中插入文档
			Map<String,String> resultMap=mongoDbService.insertStudentPaper(request,file,flag);
			if(Objects.equals("-1",resultMap.get("code"))){
				return ResultHandler.fail(ResponseEnum.NOT_UPDATE);
			}

			if(Objects.equals("0",resultMap.get("code"))){
				return ResultHandler.success();
			}

			// 向Mysql中写入一条记录
//			StudentWithReport studentWithReport=new StudentWithReport();
//			studentWithReport.setStudentId((Integer) request.getAttribute("userName"));
//			studentWithReport.setFileName(fileName);
//			if(fileRecordService.insertOneRecord(studentWithReport)){
//				return ResultHandler.success(fileName);
//			}
		}
		return ResultHandler.fail(ResponseEnum.INSERT_ERROR);
	}


	@GetMapping("/openAndPapers")
	@com.zkq.graduate.annotation.Student
	@ApiOperation(value = "学生查看毕业设计与开题报告的上传记录")
	public ResultHandler<StudentWithReport> findStudentAll(HttpServletRequest request){
		Object studentId= request.getAttribute("account");
		Map<String, Object> map=new LinkedHashMap<>();
		map.put("studentId",studentId);
		// 开题报告和毕业论文记录
		List<String> fields=new ArrayList<>();
		fields.add("fileName");
		fields.add("uploadTime");
		fields.add("status");
		fields.add("isLast");
		fields.add("studentId");
		List<StudentWithReport> result=mongoDbService.findStudentPaper(map,"",fields);
		// 上传的毕业设计记录
		List<StudentWithReport> design=fileRecordService.findByStudentId(String.valueOf(studentId));
		result.addAll(design);
		return ResultHandler.success(result);
	}

	@PostMapping("/design")
	@LimitTime
	@com.zkq.graduate.annotation.Student
	@ApiOperation(value = "学生上传毕业设计")
	public ResultHandler<String> uploadDesign(
			HttpServletRequest request,
			MultipartFile file){

		if(file!=null){
			String studentId= (String) request.getAttribute("account");
			// 上传文件
			Map<String,String> result=studentService.uploadDesign(file,studentId);
			// 写入上传记录--先更新先前记录问非最新记录,再插入记录
			StudentWithReport stu=StudentWithReport.builder()
					.isLast(false)
					.studentId(studentId)
					.build();
			fileRecordService.updateByStudentId(stu);
			if(Objects.equals("0",result.get("code"))){
				stu.setFileName(file.getOriginalFilename());
				stu.setUploadTime(LocalDateTimeUtil.getStringNow());
				stu.setLast(true);
				stu.setFilePath(result.get("filePath"));
				if(fileRecordService.insertOneRecord(stu)){
					return ResultHandler.success();
				}
			}
		}
		return ResultHandler.fail(ResponseEnum.UPLOAD_FAILURE);
	}
}
